import config from '@/config'
import platform from '@/config/platform'
import { platformLogout } from '@/libs/login'
import { getEnumeration } from '../api/common'
import _ from 'lodash'
export const forEach = (arr, fn) => {
    if (!arr.length || !fn) return
    let i = -1
    let len = arr.length
    while (++i < len) {
        let item = arr[i]
        fn(item, i, arr)
    }
}

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的交集, 两个数组的元素为数值或字符串
 */
export const getIntersection = (arr1, arr2) => {
    let len = Math.min(arr1.length, arr2.length)
    let i = -1
    let res = []
    while (++i < len) {
        const item = arr2[i]
        if (arr1.indexOf(item) > -1) res.push(item)
    }
    return res
}

export const hasShow = (e) => {
    return !!e
}

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @description 得到两个数组的并集, 两个数组的元素为数值或字符串
 */
export const getUnion = (arr1, arr2) => {
    return Array.from(new Set([...arr1, ...arr2]))
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (targetarr, arr) => {
        return targetarr.some(_ => arr.includes(_))
            // return true
    }
    /**
     * @param {Object} to 目标路由
     * @param {Array} access 所有权限的数组
     * @param {Array} routes 需要查询的路由数组
     * @param {Function} next 放行
     * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
     */
export const goHasRoute = (to, access, routes, next) => {
        if (to.name === config.homeName) {
            // 找到第一个具有权限的路由
            var item = routes.find(it =>
                    it.meta.access && hasOneOf(it.meta.access, access)
                )
                // 找到这个路由中的第一个具有权限的子路由，然后跳转
            var childItem = item.children.find(it => it.meta.access && hasOneOf(it.meta.access, access))
            next({...childItem })
        } else {
            next({ name: 'error_404' })
        }
    }
    /**
     * @param {String|Number} value 要验证的字符串或数值
     * @param {*} validList 用来验证的列表
     */
export function oneOf(value, validList) {
    for (let i = 0; i < validList.length; i++) {
        if (value === validList[i]) {
            return true
        }
    }
    return false
}

/**
 * @param {Number} timeStamp 判断时间戳格式是否是毫秒
 * @returns {Boolean}
 */
const isMillisecond = timeStamp => {
    const timeStr = String(timeStamp)
    return timeStr.length > 10
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} currentTime 当前时间时间戳
 * @returns {Boolean} 传入的时间戳是否早于当前时间戳
 */
const isEarly = (timeStamp, currentTime) => {
    return timeStamp < currentTime
}

/**
 * @param {Number} num 数值
 * @returns {String} 处理后的字符串
 * @description 如果传入的数值小于10，即位数只有1位，则在前面补充0
 */
const getHandledValue = num => {
    return num < 10 ? '0' + num : num
}

/**
 * @param {Number} timeStamp 传入的时间戳
 * @param {Number} startType 要返回的时间字符串的格式类型，传入'year'则返回年开头的完整时间
 */
export const getDate = (timeStamp, startType) => {
    const d = new Date(timeStamp)
    const year = d.getFullYear()
    const month = getHandledValue(d.getMonth() + 1)
    const date = getHandledValue(d.getDate())
    const hours = getHandledValue(d.getHours())
    const minutes = getHandledValue(d.getMinutes())
    const second = getHandledValue(d.getSeconds())
    let resStr = ''
    if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
    else resStr = month + '-' + date + ' ' + hours + ':' + minutes
    return resStr
}

export const getFormatDate = (timeStamp, startType) => {
    const d = new Date(timeStamp)
    const year = d.getFullYear()
    const month = getHandledValue(d.getMonth() + 1)
    const date = getHandledValue(d.getDate())
    const hours = getHandledValue(d.getHours())
    const minutes = getHandledValue(d.getMinutes())
    const second = getHandledValue(d.getSeconds())
    let resStr = ''
    if (startType === 'year') resStr = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + second
    else resStr = year + '-' + month + '-' + date
    return resStr
}

/**
 * @param {String|Number} timeStamp 时间戳
 * @returns {String} 相对时间字符串
 */
export const getRelativeTime = timeStamp => {
    const IS_MILLISECOND = isMillisecond(timeStamp)

    if (IS_MILLISECOND) Math.floor(timeStamp /= 1000)

    timeStamp = Number(timeStamp)

    const currentTime = Math.floor(Date.parse(new Date()) / 1000)

    const IS_EARLY = isEarly(timeStamp, currentTime)

    let diff = currentTime - timeStamp

    if (!IS_EARLY) diff = -diff
    let resStr = ''
    const dirStr = IS_EARLY ? '前' : '后'

    if (diff <= 59) resStr = diff + '秒' + dirStr

    else if (diff > 59 && diff <= 3599) resStr = Math.floor(diff / 60) + '分钟' + dirStr

    else if (diff > 3599 && diff <= 86399) resStr = Math.floor(diff / 3600) + '小时' + dirStr

    else if (diff > 86399 && diff <= 2623859) resStr = Math.floor(diff / 86400) + '天' + dirStr

    else if (diff > 2623859 && diff <= 31567859 && IS_EARLY) resStr = getDate(timeStamp)
    else resStr = getDate(timeStamp, 'year')
    return resStr
}

/**
 * @returns {String} 当前浏览器名称
 */
export const getExplorer = () => {
    const ua = window.navigator.userAgent
    const isExplorer = (exp) => {
        return ua.indexOf(exp) > -1
    }
    if (isExplorer('MSIE')) return 'IE'
    else if (isExplorer('Firefox')) return 'Firefox'
    else if (isExplorer('Chrome')) return 'Chrome'
    else if (isExplorer('Opera')) return 'Opera'
    else if (isExplorer('Safari')) return 'Safari'
}

/**
 * @description 绑定事件 on(element, event, handler)
 */
export const on = (function() {
    if (document.addEventListener) {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.addEventListener(event, handler, false)
            }
        }
    } else {
        return function(element, event, handler) {
            if (element && event && handler) {
                element.attachEvent('on' + event, handler)
            }
        }
    }
})()

/**
 * @description 解绑事件 off(element, event, handler)
 */
export const off = (function() {
    if (document.removeEventListener) {
        return function(element, event, handler) {
            if (element && event) {
                element.removeEventListener(event, handler, false)
            }
        }
    } else {
        return function(element, event, handler) {
            if (element && event) {
                element.detachEvent('on' + event, handler)
            }
        }
    }
})()

/**
 * 判断一个对象是否存在key，如果传入第二个参数key，则是判断这个obj对象是否存在key这个属性
 * 如果没有传入key这个参数，则判断obj对象是否有键值对
 */
export const hasKey = (obj, key) => {
    if (key) return key in obj
    else {
        let keysArr = Object.keys(obj)
        return keysArr.length
    }
}

/**
 * @param {*} obj1 对象
 * @param {*} obj2 对象
 * @description 判断两个对象是否相等，这两个对象的值只能是数字或字符串
 */
export const objEqual = (obj1, obj2) => {
    const keysArr1 = Object.keys(obj1)
    const keysArr2 = Object.keys(obj2)
    if (keysArr1.length !== keysArr2.length) return false
    else if (keysArr1.length === 0 && keysArr2.length === 0) return true

    else return !keysArr1.some(key => obj1[key] != obj2[key])
}

export const uploadImgUrl = (status = 1) => {
    return process.env.NODE_ENV === 'development' ? config.baseUrl.dev + '/platform-file/file/img/upload?status=' + status + '&local=' + 1 : process.env.NODE_ENV === 'testing' ? config.baseUrl.test + '/platform-file/file/img/upload?status=' + status + '&local=' + 1 : config.baseUrl.pro + '/platform-file/file/img/upload?status=' + status + '&local=' + 1
}

/**
 * 防抖
 * @param {Function} func 要执行的回调函数
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timeout
export function Debounce(func, wait = 300, immediate = false) {
    if (timeout !== null) clearTimeout(timeout)

    if (immediate) {
        var callNow = !timeout
        timeout = setTimeout(function() {
            timeout = null
        }, wait)
        if (callNow) typeof func === 'function' && func()
    } else {
        timeout = setTimeout(function() {
            typeof func === 'function' && func()
        }, wait)
    }
}
/**
 * @param {*} val 日期
 * @param {*} String 日期格式年月日
 * @description 处理日期
 */
export const dateModification = (val) => {
    if (val) {
        let date = new Date(val)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        month = month <= 9 ? '0' + month : month
        let day = date.getDate()
        day = day <= 9 ? '0' + day : day
        let datatime = year + '-' + month + '-' + day
        return datatime
    }
}

/**
 * @param { 获取枚举 }
 */
export const getEnumerations = async(arr) => {
        var obj = {}
        for (var i = 0; i < arr.length; i++) {
            var { data } = await getEnumeration(arr[i])
            obj[arr[i].name || arr[i].type] = data
        }
        return Promise.resolve(obj)
    }
    // 过滤树
export const filterTree = (arr, boolean = false) => {
        arr.forEach((el) => {
            el.label = el.name
            el.value = el.id
            if (boolean) {
                if (el.rank == 3) {
                    delete el.children
                }
            }
            if (el.children && el.children.length) {
                filterTree(el.children, boolean)
            }
        })
        return arr
    }
    // 禁用子集为空的树
export const filterTreeDis = (arr) => {
        arr.forEach((el) => {
            el.label = el.name
            el.value = el.id
            if (el.rank != 4 && el.children.length == 0) {
                el.disabled = true
            }
            if (el.children && el.children.length) {
                filterTreeDis(el.children)
            }
        })
        return arr
    }
    // 过滤组织审核人/并且禁用无数据的数据
export const filterPeople = (arr, field = 'userList', rank = 5) => {
        arr.forEach((el) => {
            el.label = el.name || el.userName
            el.value = el.id
            if (el[field] && el[field].length) {
                el[field].forEach(it => { it.rank = el.rank + 1, it.parentId = el.id })
                el.children = el[field]
            }
            if (el.rank != rank && el.children.length == 0) {
                el.disabled = true
            }
            if (el.children && el.children.length) {
                filterPeople(el.children, field, rank)
            }
        })
        return arr
    }
    // 过滤org(回显、向上递归)
export const filterOrg = (arr, id, values = [], treeList) => {
        arr.forEach((el) => {
            if (el.id == id) {
                values.unshift(el.id)
                filterOrg(treeList, el.parentId, values, treeList)
                return
            }
            if (el.children && el.children.length) {
                filterOrg(el.children, id, values, treeList)
            }
        })
        return values
    }
    // 过滤设备
export const filterDeviceList = (arr) => {
        arr.forEach((el) => {
            // 找到设备 赋值给children
            if (el.deviceVos && el.deviceVos.length) {
                el.deviceVos.forEach(it => {
                    it.name = it.equipmentName;
                    it.rank = 4;
                })
                el.children = el.deviceVos
            }
            // 找到children为空的删除 防止可以点开
            if (el.children && el.children.length == 0) {
                delete el.children
            }
            // 找到没有children并且不是最后一级的禁用
            if (!el.children && el.rank != 4) {
                el.disabled = true
                el.isDisabled = true
            }
            if (el.children && el.children.length) {
                filterDeviceList(el.children)
                    // 过滤所有子元素是否是禁用
                if (el.children.every(it => it.disabled == true || el.isDisabled == true)) {
                    el.disabled = true
                    el.isDisabled = true
                }
            }
        })
        return arr
    }
    // 过滤org(回显、向上递归)
export const filterOrgName = (arr, id, values = [], treeList) => {
        arr.forEach((el) => {
            if (el.id == id) {
                values.unshift({
                    id: el.id,
                    name: el.name, //名字
                    rank: el.rank //等级
                })
                filterOrgName(treeList, el.parentId, values, treeList)
                return
            }
            if (el.children && el.children.length) {
                filterOrgName(el.children, id, values, treeList)
            }
        })
        return values
    }
    // 求两个日期之间的日期
export const getAll = (begin, end, sprit, pattern) => {
    let arr1 = begin.split(sprit || '-')
    let arr2 = end.split(sprit || '-')
    let arr1_ = new Date()
    let arrTime = []
    arr1_.setUTCFullYear(arr1[0], arr1[1] - 1, arr1[2])
    let arr2_ = new Date()
    arr2_.setUTCFullYear(arr2[0], arr2[1] - 1, arr2[2])
    let unixDb = arr1_.getTime()
    let unixDe = arr2_.getTime()
    for (let k = unixDb; k <= unixDe;) {
        arrTime.push(datetimeparse(k, pattern))
        k = k + 24 * 60 * 60 * 1000
    }
    return arrTime
}

// 时间格式处理
export const datetimeparse = (timestamp, format, prefix) => {
        if (typeof timestamp === 'string') {
            timestamp = Number(timestamp)
        };
        // 转换时区
        let currentZoneTime = new Date(timestamp)
        let currentTimestamp = currentZoneTime.getTime()
        let offsetZone = currentZoneTime.getTimezoneOffset() / 60 // 如果offsetZone>0是西区，西区晚
        let offset = null
            // 客户端时间与服务器时间保持一致，固定北京时间东八区。
        offset = offsetZone + 8
        currentTimestamp = currentTimestamp + offset * 3600 * 1000

        let newtimestamp = null
        if (currentTimestamp) {
            if (currentTimestamp.toString().length === 13) {
                newtimestamp = currentTimestamp.toString()
            } else if (currentTimestamp.toString().length === 10) {
                newtimestamp = currentTimestamp + '000'
            } else {
                newtimestamp = null
            }
        } else {
            newtimestamp = null
        };
        let dateobj = newtimestamp ? new Date(parseInt(newtimestamp)) : new Date()
        let YYYY = dateobj.getFullYear()
        let MM = dateobj.getMonth() > 8 ? dateobj.getMonth() + 1 : '0' + (dateobj.getMonth() + 1)
        let DD = dateobj.getDate() > 9 ? dateobj.getDate() : '0' + dateobj.getDate()
        let HH = dateobj.getHours() > 9 ? dateobj.getHours() : '0' + dateobj.getHours()
        let mm = dateobj.getMinutes() > 9 ? dateobj.getMinutes() : '0' + dateobj.getMinutes()
        let ss = dateobj.getSeconds() > 9 ? dateobj.getSeconds() : '0' + dateobj.getSeconds()
        let output = ''
        let separator = '-'
        if (format) {
            separator = format.match(/-/) ? '-' : '/'
            output += format.match(/yy/i) ? YYYY : ''
            output += format.match(/MM/) ? (output.length ? separator : '') + MM : ''
            output += format.match(/dd/i) ? (output.length ? separator : '') + DD : ''
            output += format.match(/hh/i) ? (output.length ? ' ' : '') + HH : ''
            output += format.match(/mm/) ? (output.length ? ':' : '') + mm : ''
            output += format.match(/ss/i) ? (output.length ? ':' : '') + ss : ''
        } else {
            output += YYYY + separator + MM + separator + DD
        }
        output = prefix ? (prefix + output) : output

        return newtimestamp ? output : ''
    }
    //   返回日期补‘0’
export const getZero = (num) => {
        // 单数前面加0
        if (parseInt(num) < 10) {
            num = '0' + num
        }
        return num
    }
    // 获取日期格式
export const formatterDate = (dt, format) => {
        let output = ''
        let separator = '-'
        var y = getZero(dt.getFullYear())
        var mon = getZero(dt.getMonth() + 1)
        var day = getZero(dt.getDate())
        var h = getZero(dt.getHours())
        var min = getZero(dt.getMinutes())
        var sec = getZero(dt.getSeconds())
        if (format) {
            separator = format.match(/-/) ? '-' : '/'
            output += format.match(/yy/i) ? y : ''
            output += format.match(/MM/) ? (output.length ? separator : '') + mon : ''
            output += format.match(/dd/i) ? (output.length ? separator : '') + day : ''
            output += format.match(/hh/i) ? (output.length ? ' ' : '') + h : ''
            output += format.match(/mm/) ? (output.length ? ':' : '') + min : ''
            output += format.match(/ss/i) ? (output.length ? ':' : '') + sec : ''
        } else {
            output += y + separator + mon + separator + day
        }
        return output
    }
    // 计算日期(添加)
export const addDate = (date, days, custom = 'add', dateType = "date") => {
        var date = new Date(date);
        switch (dateType) {
            case 'date':
                date = doDays(date, days, custom)
                break;
            case 'month':
                date = doMonths(date, days, custom)
                break;
        }
        var year = date.getFullYear();
        var month = getZero(date.getMonth() + 1);
        var day = getZero(date.getDate());
        var time = year + "-" + month + "-" + day
        return time;
    }
    // 计算日期(天数)
export const doDays = (date, days, custom) => {
        if (custom == 'add') {
            date.setDate(date.getDate() + days);
        } else if (custom == 'sub') {
            date.setDate(date.getDate() - days);
        }
        return date
    }
    // 计算日期(月份)
export const doMonths = (date, months, custom) => {
        if (custom == 'add') {
            date.setMonth(date.getMonth() + months);
        } else if (custom == 'sub') {
            date.setMonth(date.getMonth() - months);
        }
        return date
    }
    // 下载excel
export const downLoadExcel = (res, name = '节目') => {
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        let arr = res.headers["content-disposition"] ?
            res.headers["content-disposition"].split("filename=") : [];
        let filename = decodeURIComponent(arr[1]);
        downloadElement.download = filename || name;
        // document.body.appendChild(downloadElement)
        downloadElement.click()
            // document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
    }
    // 强制失焦
export const btnBlur = () => {
        let target = event.target;
        if (target.nodeName == "SPAN") {
            target = target.parentNode;
            if (target.nodeName == "SPAN") {
                target = target.parentNode;
                if (target.nodeName == "SPAN") {
                    target = target.parentNode;
                }
            }
        }
        target.blur();
    }
    // 过滤组织名称
export const formatterOrgName = (obj) => {
        return obj ? obj.twoOrgName + "/" + obj.fourOrgName : "无";
    }
    // 查找当前点击对象
export const findTarget = (e) => {
        if (e.className && e.className.includes('ivu-btn')) {
            return true
        }
        if (e.parentNode) {
            return findTarget(e.parentNode)
        } else {
            return false
        }
    }
    // 设置localStorage
export const setLocal = (field, obj) => {
        localStorage.setItem(field, JSON.stringify(obj))
    }
    // 获取localStorage
export const getLocal = (field) => {
    var it = JSON.parse(localStorage.getItem(field))
    return it ? it : {}
}
export const carStatus = {
        1: '申请人：',
        2: '审核通过：',
        3: '审核拒绝：',
        4: '人工取消：',
        5: '使用：',
        6: '打印人：',
        7: '人工作废：'
    }
    // 设置定时器
export const setTimer = (callback, timeObj = {}, timing = 300000) => {
        timeObj['timing' + Math.random()] = setInterval(() => {
            callback()
        }, timing);
    }
    // 清除定时器
export const clearTimer = (timeObj = {}) => {
    // 遍历清除定时器
    Object.keys(timeObj).forEach(it => {
        clearInterval(timeObj[it])
        delete timeObj[it]
    })
}

// 参数是否为空 空显示-
export const isEmpty = (value) => {
    return value ? value : '-'
}

// 获取矩形四个点位
export const getPoint = (elementData) => {
        var options = elementData.options
        var arr = []
        options.forEach(el => {
            arr = arr.concat(el.children.map(ele => ele))
        })
        var point = arr.filter(
            (el) => el.drop == "x" || el.drop == "y"
        );
        var width = arr.find(it => it.drop == 'width').value
        var height = arr.find(it => it.drop == 'height').value
        var x = point[0].value
        var y = point[1].value
        var points = [{ x: Number(x), y: Number(y) }, { x: Number(x) + Number(width), y: Number(y) }, { x: Number(x) + Number(width), y: Number(y) + Number(height) }, { x: Number(x), y: Number(y) + Number(height) }]
        return points
    }
    // 查找图层title
export const setTitle = (list) => {
        list.forEach((it) => {
            if (it.mediaType == 2) { //文本
                var options = JSON.parse(it.mediaContent);
                // 查找文本内容
                var contentItem;
                options.forEach((el) => {
                    contentItem = el.children.find((ele) => ele.drop == "content");
                });
                it.title = contentItem && contentItem.value || '';
            } else if (it.mediaType == 5) { //图片
                list
                    .filter((it) => it.type == 5)
                    .forEach((it, index) => {
                        it.title = "图片" + (index + 1);
                    });
            } else if (it.mediaType == 4) { //视频
                list
                    .filter((it) => it.type == 4)
                    .forEach((it, index) => {
                        it.title = "视频" + (index + 1);
                    });
            } else if (it.mediaType == 6) { //网页
                list
                    .filter((it) => it.type == 6)
                    .forEach((it, index) => {
                        it.title = "网页" + (index + 1);
                    });
            } else if (it.mediaType == 8) { //矩形
                list
                    .filter((it) => it.type == 8)
                    .forEach((it, index) => {
                        it.title = "矩形" + (index + 1);
                    });
            } else if (it.mediaType == 7) { //路线
                list
                    .filter((it) => it.type == 7)
                    .forEach((it, index) => {
                        it.title = "路线" + (index + 1);
                    });
            } else if (it.mediaType == 3) { //扩展文本
                var options = JSON.parse(it.mediaContent);
                // 查找文本内容
                var contentItem;
                options.forEach((el) => {
                    contentItem = el.children.find((ele) => ele.drop == "content");
                });
                it.title = contentItem && contentItem.value || '';
            }
        });
    }
    // 自定义超出隐藏（表格）
export const filterRender = (h, val, length) => {
    var join = val;
    let texts = "-"; // 表格列显示文字
    if (join) {
        if (join.length > length) {
            // 进行截取列显示字数
            // 需要截取的 显示省略号 并且显示tooltip提示内容
            texts = join.substring(0, length) + "...";
            return h("div", {}, [
                h(
                    "Tooltip", {
                        props: {
                            placement: "bottom",
                            transfer: true, // 是否将弹层放置于 body 内
                        },
                        style: {
                            cursor: "pointer",
                        },
                    }, [
                        // 这个中括号表示是Tooltip标签的子标签
                        texts, // 表格列显示文字
                        h(
                            "div", {
                                slot: "content",
                                style: {
                                    whiteSpace: "normal",
                                },
                            },
                            join
                        ),
                    ]
                ),
            ]);
        } else {
            // 不需要截取的  直接显示内容，不需要tooltip提示
            texts = join;
            return h('span', {}, texts)
        }
    } else {
        // 没有val值的  直接显示'-'
        return h('span', {}, '-')
    }

}


var timer, refreshTimer = null;
// 20分钟后自动退出
export const refreshLogOut = (callback = () => {}, res) => {
        // 路由跳转和接口调用（不是‘退出接口’‘回首页接口’的情况下）
        var blackList = ['/oauth2/logout', '/oauth2/authorize']
        if (!res || !blackList.some(it => res.config.url.includes(it))) {
            // 切换路由、点击接口、再次打开项目操作
            // clearTimeout(timer)
            // timer = setTimeout(() => {
            var dt = new Date().getTime();
            var refreshTime = localStorage.getItem('refreshTime');
            if (refreshTime) {
                if (dt - refreshTime >= 1200000) {
                    clearTimeout(refreshTimer)
                    alert('长时间不操作，自动退出');
                    callback(false)
                        // 清除定时器的退出登录
                    platformLogout()
                    return
                }
            }
            callback(true)
                // 每次请求接口 同时存储最后一次调取接口的时间戳
            localStorage.setItem('refreshTime', dt)
                // }, 350);


            // 主打定时器 自动退出操作
            clearTimeout(refreshTimer)
            refreshTimer = setTimeout(() => {
                alert('长时间不操作，自动退出');
                platformLogout()
            }, 1200000);
        }

    }
    // 找到类名为xxx的父级元素
export const findParent = (target, className = 'fan-form') => {
    if (target.$el.className.includes(className)) {
        return target
    } else {
        return findParent(target.$parent, className)
    }
}

// 注意:小时必须是二十四小时制 比较时分秒大小
export const HMS_daxiao = (str1, str2) => {
    // 方法一:将时分转化为毫秒数
    // let YMD = '2021/10/1 '; // 只是进行时分秒的大小比较，年月为任意时间都行
    // str1 = new Date(YMD + str1).getTime();
    // str2 = new Date(YMD + str2).getTime();
    // 小于0则str1时间小，大于0则str1时间大
    // return str1 - str2

    // 方法二:将时分秒手动转化为秒数
    let arr1 = str1.split(':');
    let arr2 = str2.split(':');
    str1 = Number(arr1[0]) * 3600 + Number(arr1[1]) * 60 + Number(arr1[2]);
    str2 = Number(arr2[0]) * 3600 + Number(arr2[1]) * 60 + Number(arr2[2]);
    // 小于0则str1时间小，大于0则str1时间大
    return str1 - str2

    // 方法二:将时分秒转化为数字
    // let arr1 = str1.split(':');
    // let arr2 = str2.split(':');
    // arr1[0] < 10 ? arr1[0] = '0' + arr1[0] : ''; //将小时转化为两位数
    // arr1[1] < 10 ? arr1[1] = '0' + arr1[1] : ''; //将分钟转化为两位数
    // arr1[1] < 10 ? arr1[1] = '0' + arr1[1] : ''; //将秒转化为两位数
    // arr2[0] < 10 ? arr2[0] = '0' + arr2[0] : '';
    // arr2[1] < 10 ? arr2[1] = '0' + arr2[1] : '';
    // arr2[1] < 10 ? arr2[1] = '0' + arr2[1] : '';
    // str1 = Number(arr1.join(''));
    // str2 = Number(arr2.join(''));
    // 小于0则str1时间小，大于0则str1时间大
    // return str1 - str2
};

export default {
    getEnumerations,
    filterTree,
    filterTreeDis,
    filterOrg,
    getZero,
    getAll,
    formatterDate,
    hasOneOf,
    goHasRoute,
    downLoadExcel,
    filterOrgName,
    addDate,
    carStatus,
    datetimeparse,
    btnBlur,
    formatterOrgName,
    filterPeople,
    findTarget,
    setLocal,
    getLocal,
    setTimer,
    clearTimer,
    isEmpty,
    setTitle,
    getPoint,
    filterDeviceList,
    filterRender,
    refreshLogOut,
    findParent,
    HMS_daxiao
}